package org.example.classtopia.Service.Impl;


import lombok.extern.slf4j.Slf4j;
import org.example.classtopia.Mapper.CourseMapper;
import org.example.classtopia.Model.Entity.Course;
import org.example.classtopia.Model.Entity.Schedule;
import org.example.classtopia.Service.AiScheduleService;
import org.example.classtopia.Utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@Service
public class AiScheduleServiceImpl implements AiScheduleService {

    @Autowired
    private CourseMapper courseMapper;

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;


    @Override
    public List<Schedule> getSchedules(LocalDate Date, String semester, Long userId) {

        Integer dayOfWeek = DayOfWeek.from(Date).getValue();
        Integer week = DateUtils.calculateCurrentWeek(semester, Date);
        List<Course> courses = courseMapper.selectCoursesByUserAndWeekAndDay(userId, semester, week, dayOfWeek);
        if (courses.isEmpty()) {
            log.error("获取日程信息失败！");
            return new ArrayList<>();
        }
        List<Schedule> schedules = new ArrayList<>();

        for(Course course : courses) {
            Schedule schedule = new Schedule();
            schedule.setName(course.getName());
            schedule.setDescription(course.getDescription());
            schedule.setStartTime(course.getStartTime());
            schedule.setEndTime(course.getEndTime());
            schedule.setLocation(course.getLocation());
            schedules.add(schedule);
        }

        return schedules;
    }

    @Override
    public String generatePrompt(List<Schedule> schedules, LocalDate Date){

        StringBuilder prompt = new StringBuilder();
        prompt.append("基于以下日程信息，请帮我给出合理的日程安排建议: \n\n");
        prompt.append("日期:").append(Date).append("\n");

        for(Schedule schedule : schedules) {
            prompt.append("时间:").append(schedule.getStartTime()).append("~")
                    .append(schedule.getEndTime()).append("\n");
            prompt.append("名称:").append(schedule.getName()).append("\n");
            prompt.append("地点:").append(schedule.getLocation()).append("\n");
            prompt.append("日程描述:").append(schedule.getDescription()).append("\n");
            prompt.append("\n");
        }

        prompt.append("请根据每一条日程信息的内容，为我每一条日程活动提供活动建议，不用给出出行时间的建议\n");
        return prompt.toString();
    }

    @Override
    public String getRecommendation(String prompt) {

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-max");

        List<Map<String, String>> messages = new ArrayList<>();
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);
        messages.add(userMessage);

        requestBody.put("messages", messages);

        //调用API
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(baseUrl , entity, Map.class);

        Map<String, Object> responseBody = response.getBody();
        Map<String, Object> choices = (Map<String, Object>) ((List<?>) responseBody.get("choices")).get(0);
        Map<String, String> message = (Map<String, String>) choices.get("message");

        return message.get("content");
    }
}
